package com.sq.universe.system.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sq.universe.base.constants.BaseConstants;
import com.sq.universe.system.controller.FileCategoryController;
import com.sq.universe.system.entity.UserEntity;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;
import io.swagger.models.auth.In;
import org.crazycake.shiro.RedisSessionDAO;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    //用于记录和管理所有客户端的channle
    private static ChannelGroup clients = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    private static Map<String,Channel>  channelMap = new HashMap();

    public static Map<Integer,Channel>  userChannel = new HashMap();

    private RedisSessionDAO redisSessionDAO;

    public WebSocketHandler(RedisSessionDAO redisSessionDAO){
         this.redisSessionDAO = redisSessionDAO;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        //获取客户端传输过来的信息
        String content = msg.text();
        System.out.println("接收到的数据：" + content);
        JSONObject msgObj = JSON.parseObject(content);
        String type = msgObj.getString("type");
        if("start".equals(type)){
            String userId = msgObj.getString("userId");
            UserEntity userEntity = (UserEntity) redisSessionDAO.readSession(userId).getAttribute(BaseConstants.CURRENT_USER);
            userChannel.put(userEntity.getUserId(),ctx.channel());
        }

//        for(Channel channel : clients) {
//            channel.writeAndFlush(new TextWebSocketFrame("[服务器在]" + LocalDateTime.now()
//                    + "接收到消息，消息为：" + content));
//        }

        //与上面的for循环一致
//        clients.writeAndFlush(new TextWebSocketFrame("[服务器在]" + LocalDateTime.now()"接收到消息，消息为：" + content));
    }

    /**
     * 当客户端连接服务端之后（打开连接）
     * 获取客户端的channle,并且放到ChannelGroup中去进行管理
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        channelMap.put(ctx.channel().id().asLongText(),ctx.channel());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        //当触发handlerRemoved,ChannelGroup会自动移除客户端的channel
        clients.remove(ctx.channel().id().asLongText());
        System.out.println("客户端断开，channel对应的长id为：" + ctx.channel().id().asLongText());
        System.out.println("客户端断开，channel对应的短id为：" + ctx.channel().id().asShortText());
    }

}
